<template>
  <container type="ghost">
    <div class="theme-tab-container">
      <el-tabs v-model="activeName">
        <el-tab-pane v-for="item in tabList" :key="item.id" :name="item.id + ''" :label="item.name">
          <div v-if="item.children && item.children.length" class="card-box">
            <div
              v-for="(x, i) in item.children"
              :key="x.id"
              :style="{ background: colorList[i % colorList.length] }"
              class="card-content"
              :class="{ 'is-active': searchForm.form_type == x.id }"
              @click="onChangeType(x.id)"
              >{{ x.name }}</div
            >
          </div>
          <div v-else class="card-box-empty" flex="dir:top main:center cross:center">
            <icon name="inbox"></icon>
            <span>没有流程类型</span>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="theme-main-container">
      <!-- 搜索 -->
      <div class="filter-container">
        <el-form ref="form" :model="searchForm" label-width="80px" align="right">
          <el-row>
            <el-col :span="6">
              <el-form-item label="流程名称" prop="name">
                <el-input v-model="searchForm.name" placeholder="请输入流程名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18" class="btn-container">
              <el-button icon="el-icon-search" type="primary"  @click="search">查询</el-button>
              <el-button icon="el-icon-refresh"  @click="search('reset')">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="btn-container">
        <el-button type="primary" icon="el-icon-plus" @click="openNewDialog">新建流程</el-button>
      </div>
      <!-- table -->
      <el-table row-key="id" stripe v-loading="listLoading" :data="list" style="width: 100%">
        <el-table-column v-for="item in tableColumns" :key="item.prop" v-bind="item" >
          <template slot-scope="scope">
            <div v-if="item.prop === 'index'">{{ scope.$index + 1 }}</div>
            <div v-else-if="item.prop === 'operation'" class="operation-btn">
              <el-button icon="el-icon-setting"
                type="text"
                @click="editFlowDialog(scope.row.deploymentID, scope.row.name, scope.row.procKey)"
                >设计流程</el-button
              >
              <el-button icon="el-icon-edit"
                type="text"
                @click="
                  editSort(
                    scope.row.deploymentID,
                    scope.row.name,
                    scope.row.flowSort,
                    scope.row.procKey
                  )
                "
                >业务配置</el-button
              >
              <el-popconfirm title="您确定要删除吗？" @confirm="deleteById(scope.row)">
                <el-button icon="el-icon-delete" slot="reference" type="text" class="btn-danger">删除</el-button>
              </el-popconfirm>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="searchForm.page"
        :limit.sync="searchForm.pagesize"
        @pagination="getList"
      />

      <el-drawer
        class="flow-design"
        title="流程设计图"
        v-if="dialogVisible == true"
        :visible.sync="dialogVisible"
        size="100%"
        :append-to-body="false"
        direction="btt"
        destroy-on-close
        @close="cloaseDialog"
      >
        <vue-Bpmn
          :processId="processId"
          :deployMName="deployMName"
          :deployMId="deployMId"
          product="activiti"
        ></vue-Bpmn>
      </el-drawer>

      <el-drawer
        :title="title"
        v-if="dialogNewSortVisible == true"
        :close-on-click-modal="false"
        :visible.sync="dialogNewSortVisible"
        @close="cloaseSortDialog"
        :close-on-press-escape="false"
        destroy-on-close
        size="60%"
      >
        <div class="drawer-content">
          <el-form
            label-suffix="："
            label-width="90px"
            :model="ruleForm"
            ref="ruleForm"
            style="width: 95%"
          >
            <el-form-item label="流程名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="所属类别" prop="flowSort">
              <select-tree
                class="tree"
                v-model="value"
                :data="sortdata"
                placeholder="请选择所属类别"
              ></select-tree>
            </el-form-item>
            <el-form-item label="表单类型" prop="form_type">
              <el-select v-model="ruleForm.form_type" @change="updateElementTask('form_type')">
                <el-option label="内置表单" value="0" />
                <el-option label="外部表单" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="taskFormtype == '0'" prop="formMap" label="流程表单">
              <el-select v-model="ruleForm.formMap" filterable @change="updateAttrs">
                <el-option v-for="i in formMapList" :key="i.id" :value="i.id" :label="i.name" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="taskFormtype == '1'" prop="form_url" label="表单地址">
              <el-input
                v-model="ruleForm.form_url"
                @change="updateElementTask('form_url')"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <div v-if="taskFormtype == '0'">
                <div class="element-drawer__button">
                  <el-button size="mini" type="primary" icon="el-icon-view" @click="openView()"
                    >查看表单</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button type="primary" @click="saveEdit">保存</el-button>
          <el-button @click="cloaseSortDialog">取消</el-button>
        </div>
      </el-drawer>
      <el-drawer
        :visible.sync="viewVisible"
        title="表单预览"
        size="95%"
        class="radius"
        :append-to-body="false"
        direction="btt"
        destroy-on-close
      >
        <preview :itemList="itemList" :dataJson="[]" :formConf="formConf" />
      </el-drawer>
    </div>
  </container>
</template>

<script>
  import VueBpmn from './processDesign';
  import preview from '@/components/formcomponents/preview';
  import { flowSortTree } from '@/api/process/flowsort';
  import {
    processList,
    updataProcess,
    getFormElement,
    delDefinition
  } from '@/api/process/flowdesign';
  import { formList, getFormEntity } from '@/api/process/processFrom';
  import Pagination from '@/components/Pagination';
  import { colorList } from '@/const';
  import { tableColumns } from './const';
  import SelectTree from '@/components/selectTree/index.vue';

  export default {
    name: 'flowDefinition',
    components: { Pagination, VueBpmn, preview, SelectTree },
    data() {
      return {
        dialogVisible: false,
        dialogNewSortVisible: false,
        formMapList: [],
        viewVisible: false,
        deployMId: '',
        deployMName: '',
        processId: '',
        taskFormtype: '',
        mapJson: '',
        itemList: [],
        formConf: Object,
        value: null,
        sortdata: [],
        title: '',
        colorList,
        tabList: [],
        activeName: '',
        tableColumns,
        list: [],
        total: 0,
        listLoading: false,
        searchForm: {
          page: 1,
          pagesize: 10,
          name: '',
          sortid: ''
        },
        ruleForm: {
          id: '',
          name: '',
          form_type: '',
          formMap: '',
          form_url: '',
          sortid: this.value,
          process_key:''
        }
      };
    },
    created() {
      this.getList();
      this.getSelectData();
      this.flowSortTree();
      this.loadFormList();
    },
    methods: {
      // 获取
      getList() {
        this.listLoading = true;
        processList(this.searchForm).then((res) => {
          if (res.error === 200) {
            this.list = res.result.list;
            this.total = res.result.total;
          } else {
            this.$message.error(`获取列表失败`);
          }
          this.listLoading = false;
        });
      },
      loadFormList() {
        const params = {
          name:'',
          form_type:'',
          page: 1,
          pagesize: 0
        };
        formList(params).then((res) => {
          if (res.error == '200') {
            this.formMapList = res.result.list;
          } else {
            this.$message.error('获取失败');
          }
          this.loading = false;
        });
      },
      flowSortTree() {
        flowSortTree().then((res) => {
          if (res.error == '200') {
            this.sortdata = res.result;
          }
        });
      },
      // 新增流程
      openNewDialog() {
        this.dialogVisible = true;
        this.deployMId = '';
        this.deployMName = '';
        this.processId = '';
      },
      editFlowDialog(deploymentId, deploymentName, processId) {
        this.dialogVisible = true;
        this.deployMId = deploymentId;
        this.deployMName = deploymentName;
        this.processId = processId;
      },
      updateElementTask(key) {
        if(key=="form_type"){
          this.taskFormtype=this.ruleForm[key];
          return;
        }
        if(key=="form_url"){
          this.taskFormtype=this.ruleForm[key];
          return;
        }
      },
      cloaseDialog() {
        this.deploy();
      },
      deploy() {
        this.getList();
        this.getSelectData();
      },
      // dialog关闭事件
      cloaseSortDialog() {
        this.dialogNewSortVisible = false;
        this.deploy();
      },
      saveEdit() {
        this.ruleForm.sortid = this.value;
        updataProcess(this.ruleForm).then((res) => {
          if (res.error == '200') {
            this.$message.success('修改成功');
            this.dialogNewSortVisible = false;
            setTimeout(() => {
              this.deploy();
            }, 1000);
          } else {
            this.$message.error('获取失败');
          }
        });
      },
      editSort(deploymentId, name, sortid, processkey) {
        this.title = '业务配置';
        this.ruleForm.name = name;
        this.ruleForm.id = deploymentId;
        this.ruleForm.process_key = processkey;
        if (sortid == 0 || sortid == null) {
          this.ruleForm.sortid = null;
          this.value = null;
        } else {
          let newSortId = sortid - 0;
          this.ruleForm.sortid = newSortId;
          this.value = newSortId;
        }
        getFormElement({ process_key: processkey }).then((res) => {
          if (res.error != '200') {
            this.mapJson = '';
            this.ruleForm.form_type = '';
            this.ruleForm.formMap = '';
            this.ruleForm.form_url = '';
            this.taskFormtype = '';
            this.dialogNewSortVisible = true;
            return;
          } else {
            if (res.result == '' || res.result == undefined) {
              this.mapJson = '';
              this.ruleForm.form_type = '';
              this.ruleForm.formMap = '';
              this.ruleForm.form_url = '';
              this.taskFormtype = '';
              this.dialogNewSortVisible = true;
              return;
            }
            if (res.result.mapJson == '' || res.result.mapJson == undefined) {
              this.mapJson = '';
            } else {
              this.mapJson = JSON.parse(res.result.mapJson);
            }
            this.ruleForm.form_type = res.result.form_type;
            this.ruleForm.formMap = res.result.formMap;
            this.ruleForm.form_url = res.result.form_url;
            this.taskFormtype = res.result.form_type;
            this.dialogNewSortVisible = true;
          }
        });
      },
      updateAttrs() {
        let selectOption = this.formMapList.filter((item) => {
          if (item.id == this.ruleForm.formMap) {
            return item;
          }
        });
        if (selectOption[0].form_json == undefined) {
          this.mapJson = undefined;
          return;
        }
        this.mapJson = JSON.parse(selectOption[0].form_json);
      },
      openView() {
        getFormEntity({ id: this.ruleForm.formMap }).then((res) => {
          if (res.error == '200') {
            this.mapJson = JSON.parse(res.result.form_json);
            if (this.mapJson == undefined) {
              this.$message.error('表单内容为空');
              return;
            } else if (this.mapJson == []) {
              this.$message.error('请选择表单');
              return;
            } else {
              this.formConf = this.mapJson.config;
              this.itemList = this.mapJson.list;
            }
            this.viewVisible = true;
          } else {
            this.$message.error('获取失败');
          }
        });
      },
      search(type) {
        if (type === 'reset') {
          this.$refs.form.resetFields();
          this.searchForm.sortid = undefined;
        }
        this.searchForm.page = 1;
        this.getList();
      },
      onChangeType(type) {
        this.searchForm.sortid = type;
        this.search();
      },
      async getSelectData() {
        const data = (await flowSortTree()).result;
        if (data.length) {
          this.tabList = data;
          this.activeName = this.tabList[0].id + '';
        }
      },
      async deleteById(row) {
        const res = await delDefinition({ depID: row.deploymentID });
        if (res.error === 200) {
          this.$message.success(`删除成功`);
          this.search('reset');
        } else {
          this.$message.error(`删除失败`);
        }
      }
    }
  };
</script>
